<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

$PJID=$param['pid'];

$listFields = array("id","name","#comment","statusid","userid","userid2","teamid","lastupdate","translated","untranslated","fuzzy","chstamp","prjname");

if ($op=="assign") {
	$ids = stripslashes($param['ids']);
	$idlist = json_decode($ids);
	$transuser = $param['userid1'];
	$revuser = $param['userid2'];
	$statusid = $param['statusid'];
	
	$failed = array();
	$notif = array();
	$notif[1]=array();
	$notif[2]=array();
	
	$duplicated = false;
	
	$prj = new project;
	$prj->id=$PJID;
	$loader->get($prj);
	$sprj = array();
	$res = array();	
	foreach ($idlist as $uid) {
		$f = new files($PJID);
		$f->id=$uid->id;
		$loader->get($f);
		$hact = HIS_ACT_UP;
		if ($f->chstamp == $uid->hash) {

			if ($transuser!="") {
				if ($transuser=="none") {
					$f->userid="";
					$hact = HIS_ACT_UASN;
					if (in_array($f->statusid, array(FILE_STATUS_TRANS,FILE_STATUS_LOCKED))) {
						$f->statusid=FILE_STATUS_TODO;	
					}
				} else {
					$hact = HIS_ACT_ASN;
					$f->userid=$transuser;
					if (in_array($f->statusid, array(FILE_STATUS_TRANS,FILE_STATUS_TODO))) {
						$f->statusid=FILE_STATUS_LOCKED;	
					}
				}
			}
			if ($revuser!="") {
				if ($revuser=="none") {
					$hact = HIS_ACT_UASN;
					$f->userid2 = "";
				} else {
					$hact = HIS_ACT_ASN;
					$f->userid2 = $revuser;
				}
				if ($f->statusid==FILE_STATUS_PROOF) {
					$f->statusid=FILE_STATUS_CHKPND;	
				}				
			}			
			
			if ($f->userid==$f->userid2 && ($f->userid!="")) {
				$duplicated=true;
			} else {
				/*if (isset($param['initstatus']) and $f->statusid==FILE_STATUS_TODO) {
					$f->statusid=FILE_STATUS_CHKPND;
				} */
				if (isset($statusid) && $statusid!="") {
					$f->statusid=$statusid;
					if ($statusid==FILE_STATUS_TODO) {
						$f->userid="";
					}
				}
				$f->comment=$param['comment'];
				$loader->update($f);
				
				array_push($res,$f);
				
				$his = new history($PJID);
				$his->statusid=$f->statusid;
				$his->fileid=$f->id;
				$his->userid=$CURRENT_USER->userid;
				$his->comment=$f->comment;
				$his->action=$hact;
				$loader->save($his);

				if (!array_key_exists($f->prjid,$sprj)) {
					$sp = new project;
					$sp->id=$f->prjid;
					$loader->get($sp);
					$sprj[$f->prjid]=$sp;
				}	else {
					$sp = $sprj[$f->prjid];
				}

				$f->subprjname=$sp->name;
				$f->prjname=$prj->name;

				if ($transuser!="" and $transuser!="none") {
					if (!array_key_exists($transuser,$notif[1])) {
						$notif[1][$transuser]=array();
					} 
					array_push($notif[1][$transuser],$f);
				}
				if ($revuser!="" and $revuser!="none") {
					if (!array_key_exists($revuser,$notif[2])) {
						$notif[2][$revuser]=array();
					} 
					array_push($notif[2][$revuser],$f);
				}

			}
		} else {
			array_push($failed,$f);
		}
	}
	
	$failmsg="";
	if (count($failed)>0) {
		$fn = "";
		foreach ($failed as $f) {
			if ($fn=="") {
				$fn = $f->name;
			} else {
				$fn .= ", " . $f->name;	
			}
		}
		if (count($failed) > 1) {
			$er = s("The files {0} were already modified by another user.");	
		} else {
			$er = s("The file {0} was already modified by another user.");
		}
		$failmsg = String::format($er,$fn);
	}
	
	if ($duplicated || count($failed)) {
		if ($duplicated) {
			$failmsg .= "<br>".s("Some files were not modified because it would set the same user as translator and reviewer.");
		}
		failed($failmsg,jsonList($res,$listFields));
	} else {
		success(jsonList($res,$listFields),false);		
	}
	
	if (count($notif[1])>0) {
		$_log->debug("Notify translator");
		foreach ($notif[1] as $key => $val) {
			mailFileAssign($key,$val,1,$param['comment']);
		}
	}
	if (count($notif[2])>0) {
		$_log->debug("Notify reviewer");
		foreach ($notif[2] as $key => $val) {
			mailFileAssign($key,$val,2,$param['comment']);
		}
	}
	
} else if ($op=="single_assign") {
	$ids = stripslashes($param['ids']);
	$idlist = json_decode($ids);
	$type = $param['type'];
	
	$failed = array();
	$forbidden = array();
	$duplicated = false;
	$notvalid = false;
	$res = array();
	foreach ($idlist as $uid) {
		$f = new files($PJID);
		$f->id=$uid->id;
		$loader->get($f);
		$er = false;
		if ($f->chstamp == $uid->hash) {
			$fstatus=$f->statusid;
			if ($type=="1") {
				// TRANSLATOR
				if ($f->userid!="" && $f->userid!=$CURRENT_USER->userid) {
					array_push($forbidden,$f);
					$er=true;
				} else {
					$f->userid=$CURRENT_USER->userid;
					$f->statusid=FILE_STATUS_LOCKED;
				}
			} else if ($type=="2") {
				// REVIEWER
				if ($f->userid2!="" && $f->userid2!=$CURRENT_USER->userid) {
					array_push($forbidden,$f);
					$er=true;
				} else {
					$f->userid2=$CURRENT_USER->userid;
				}				
			}

			if ($f->userid==$f->userid2 && ($f->userid!="")) {
				$duplicated = true;
			}
			
			if (!$er && !$duplicated) {
				switch ($param['initialstatus']) {
					case "1":
						if ($fstatus==FILE_STATUS_TODO || $fstatus==FILE_STATUS_LOCKED) {
							$f->statusid = FILE_STATUS_TRANS;	
						} else {
							$notvalid = true;
						}
						break;
					case "2":
						if ($fstatus==FILE_STATUS_CHKPND) {
							$f->statusid = FILE_STATUS_PROOF;	
						} else {
							$notvalid = true;
						}					
						break;
					default:
						break;
				}
				$f->comment=$param['comment'];
				$loader->update($f);
				
				array_push($res,$f);
				
				$his = new history($PJID);
				$his->statusid=$f->statusid;
				$his->fileid=$f->id;
				$his->userid=$CURRENT_USER->userid;
				$his->comment=$f->comment;
				$his->action=HIS_ACT_ASN;		
				$loader->save($his);
			}			
		} else {
			array_push($failed,$f);
		}
	}
	
	$ffailmsg="";
	$fforbmsg="";
	$ffvs="";
	if (count($failed)>0) {
		$fn = "";
		foreach ($failed as $f) {
			if ($fn=="") {
				$fn = $f->name;
			} else {
				$fn .= ", " . $f->name;	
			}
		}
		if (count($failed) > 1) {
			$ffail = s("The files {0} were already modified by another user.");	
		} else {
			$ffail = s("The file {0} was already modified by another user.");
		}
		$ffailmsg = String::format($ffail,$fn);
	}
	if (count($forbidden)>0) {
		$fn = "";
		foreach ($forbidden as $f) {
			if ($fn=="") {
				$fn = $f->name;
			} else {
				$fn .= ", " . $f->name;	
			}
		}
		if (count($forbidden) > 1) {
			$fforb = s("The files {0} are already assigned to another user.");	
		} else {
			$fforb = s("The file {0} is already assigned to another user.");
		}
		$fforbmsg = String::format($fforb,$fn);	
	}
	if ($notvalid) {
		$ffvs = s("Couldn't set initial status on all files.");
	}
	if (count($failed)>0 || count($forbidden)>0 || $duplicated || $notvalid) {
		if ($duplicated) {
			if ($fforbmsg!="") $fforbmsg .="<br>";
			$fforbmsg .= s("Some files were not modified because it would set the same user as translator and reviewer.");
		}
		$fmsg=$ffailmsg;
		if ($fforbmsg!="") {
			if ($fmsg!="") $fmsg.="<br/>";
			$fmsg.= $fforbmsg;
		}
		if ($ffvs!="") {
			if ($fmsg!="") $fmsg.="<br/>";
			$fmsg.= $ffvs;
		}
		failed($fmsg,jsonList($res,$listFields));
	} else {
		success(jsonList($res,$listFields),false);	
	}

} else if ($op=="save") {

	$ids = stripslashes($param['ids']);
	$idlist = json_decode($ids);
/*
	if ($CURRENT_USER->groupid == GROUP_COORD) {
		$userid = $param['userid']!="" ? $param['userid'] : $CURRENT_USER->userid;	
	} else {
		$userid = $CURRENT_USER->userid;
	}
*/
	$forbidden = array();
	$failed = array();	
	$invalid = array();
	$res = array();
	foreach ($idlist as $uid) {
		$f = new files($PJID);
		$f->id=$uid->id;
		$loader->get($f);
		$fail = false;
		if ($f->chstamp == $uid->hash) { // || in_array($CURRENT_USER->userid,array($f->userid,$f->userid2))) {
			switch ($CURRENT_USER->userid) {
				case $f->userid:
					if (in_array($f->statusid,array(FILE_STATUS_PROOF,FILE_STATUS_CMPND))) {							
						$fail=true;
						array_push($invalid,$f);	
					}
					break;
				case $f->userid2:
					if (!in_array($f->statusid,array(FILE_STATUS_DONE,FILE_STATUS_PROOF,FILE_STATUS_CHKPND))) {							
						$fail=true;
						array_push($invalid,$f);	
					}
					break;
				default:
					$fail=true;
					array_push($forbidden,$f);
					break;
			}
			
			if (!$fail) {
				$f->statusid=$param['statusid'];
				$f->comment=$param['comment'];
				
				$loader->update($f);
				
				array_push($res,$f);
				
				$his = new history($PJID);
				$his->statusid=$f->statusid;
				$his->fileid=$f->id;
				$his->userid=$CURRENT_USER->userid;
				$his->comment=$f->comment;
				$his->action=HIS_ACT_UP;
				$loader->save($his);
				/*
				if ($CURRENT_USER->userid == $f->userid && $f->statusid==FILE_STATUS_CHKPND && $f->userid2!="") {
					mailFileTranslated($f->userid2,$f,$f->comment);
				}*/
			}
		} else {
			array_push($failed,$f);
		}			
	}
	
	$failmsg = "";
	if (count($failed)>0) {
		$fn = "";
		foreach ($failed as $f) {
			if ($fn=="") {
				$fn = $f->name;
			} else {
				$fn .= ", " . $f->name;	
			}
		}
		if (count($failed) > 1) {
			$er = s("The files {0} were already modified by another user.");	
		} else {
			$er = s("The file {0} was already modified by another user.");
		}
		$failmsg = String::format($er,$fn);	
	}

	if (count($forbidden)>0) {
		if ($failmsg!="") $failmsg.="<br/>";
		$failmsg.=s("Some of the selected files are not assigned to you.");
	}
	if (count($invalid)>0) {
		if ($failmsg!="") $failmsg.="<br/>";
		$failmsg.=s("Some of the selected files cannot be edited right now.");
	}

	if ($failmsg!="") {
		failed($failmsg,jsonList($res,$listFields));
	} else {
		success(jsonList($res,$listFields),false);	
	}
	
} else if ($op=="free") {

	$ids = stripslashes($param['ids']);
	$idlist = json_decode($ids);

	$failed = array();	
	$res = array();
	foreach ($idlist as $uid) {
		$fail = false;
		$f = new files($PJID);
		$f->id=$uid->id;
		$loader->get($f);
		
		switch ($CURRENT_USER->userid) {
			case $f->userid:
				$_log->debug("Translator");
				$f->userid="";
				if (in_array($f->statusid,array(FILE_STATUS_LOCKED,FILE_STATUS_TRANS))) {
					$f->statusid=FILE_STATUS_TODO;
				}
				break;
			case $f->userid2:
				$_log->debug("Reviewer");
				$f->userid2="";
				if ($f->statusid==FILE_STATUS_PROOF) {
					$f->statusid=FILE_STATUS_CHKPND;
				}				
				break;				
			default:
				$_log->debug("Not assigned");
				$fail = true;
				array_push($failed,$f);
				break;
		}
		
		if (!$fail) {
			$f->comment=$param['comment'];
			
			$loader->update($f);
	
			array_push($res,$f);
					
			$his = new history($PJID);
			$his->statusid=$f->statusid;
			$his->fileid=$f->id;
			$his->userid=$CURRENT_USER->userid;
			$his->comment=$f->comment;
			$his->action=HIS_ACT_FREE;
			$loader->save($his);
			
			if ($f->statusid == FILE_STATUS_TODO) {
				$_log->debug("Notify coordinators");
				mailFileFree($CURRENT_USER,$f,$f->comment);
			}
		}
		
	}
	
	if (count($failed)>0) {
		$fn = "";
		foreach ($failed as $f) {
			if ($fn=="") {
				$fn = $f->name;
			} else {
				$fn .= ", " . $f->name;	
			}
		}
		if (count($failed) > 1) {
			$er = s("The files {0} were not modified because are not assigned to you.");	
		} else {
			$er = s("The file {0} was not modified because is not assigned to you.");
		}
		failed(String::format($er,$fn),jsonList($res,$listFields));
	} else {
		success(jsonList($res,$listFields),false);	
	}
} else if ($op=="gal") {
	$TEAMID = getTeamId($CURRENT_USER);
	$files = new files($PJID);
	$files->teamid = $TEAMID;
	$list = $loader->loadListBy($files,$files->loadAssList());
	$fname = "list.".rand(10000,99999);
	$filename = TEMP_PATH."/".$fname;
	$sep = ",";
	$str=s("File").$sep.s("Translator").$sep.s("Reviewer").$sep.s("Status");
	foreach ($list as $f) {
		$str.="\n";
		$str .=$f->name.$sep;
		if ($f->userid!="") {
			$str.= $f->userid.$sep;
		} else {
			$str.= "-".$sep;
		}
		if ($f->userid2!="") {
			$str.= $f->userid2.$sep;
		} else {
			$str.= "-".$sep;
		}
		$str.=utf8_decode(s($DEF_TRANS[$f->statusid],null,true));
	}
	if (file_exists($filename)) {
		@unlink($filename);
	}
	$out = fopen($filename,"w");
	fwrite($out,$str);
	fclose($out);
	@chmod($filename,0666);
	$r = "[{file: '".$fname."', name: 'list.csv'}]";
	success($r,false);
} else {
	$TEAMID = getTeamId($CURRENT_USER);

	$files = new files($PJID);
	$files->teamid = $TEAMID;
	$files->totalrecord = $param['limit'];
	$files->record = !isset($param['start']) ? 0 : $param['start'];
	if ($param['sort']!="") {
		$files->order=$param['sort'];	
	}
	$files->orderDir=$param['dir'];
	$q = null;
	if (isset($param['filter'])) {
		$filters = $param['filter'];
		foreach ($filters as $obj) {
			if ($obj['data']['type']=="list") {
				$filter = util::stringToArray($obj['data']['value'],",");
				if (count($filter)==1) $filter = $filter[0];
			} else {
				$filter = $obj['data']['value'];
			}
			switch ($obj['field']) {
				case "statusid":
					$files->statusid=$filter;
					break;
				case "name":
					$files->name=$filter;
					break;
				case "translator":
					$files->userid=$filter;
					break;
				case "reviewer":
					$files->userid2=$filter;
					break;
				case "prjname":
					$files->prjid=$filter;
					break;
				default:
					break;
			}
		}
	}
	
	if ($param['q']!="all") {
		switch ($param['q'] ) {
			case "mf":
				$q = $CURRENT_USER->userid;	
				break;
			case "un":
				$files->st=4;			
				break;
			default:
				break;
		}
	}

	$list = $loader->loadListBy($files,$files->loadfiltered(false,$q));
	$TOTALRECCOUNT = $loader->fetchcount($files->loadfiltered(true,$q));
	
	out(jsonList($list,$listFields,null,$TOTALRECCOUNT));	
}

?>